<?php


class AuthDao {

	
	/**
	 * 
	 * @param PDIO $pdio
	 * @param unknown $uname
	 * @throws WrongLoginException
	 */
	public static function getHPwd($pdio, $uname) {
		
		/*$sql = "SELECT hashpwd, salt from ".AUTH_UTABLE." WHERE app_id = '".APP_ID."' AND username = '$uname'";
		$res = $pdio->query($sql);*/
		
		$sql = "SELECT hpwd, salt from ".DB_PREF.AUTH_UTABLE." WHERE uname = :uname";
		$data = array(':uname' => $uname);
		
		$res = $pdio->parametricQuery($sql, $data);

		
		if (count($res) == 0) {
			throw new WrongLoginException("utente non trovato");
		}
		
		return array($res[0]['hpwd'], $res[0]['salt']);
		
	}
	
	public static function insertToken($pdio, $uname, $token) {
		$sql = "UPDATE ".DB_PREF.AUTH_UTABLE." SET token = :token WHERE uname = :uname";
		$data = array(':uname' => $uname, ':token' => $token);
	
		return $pdio->parametricQuery($sql, $data);
	}
	
	public static function getToken($pdio, $uname) {
		$sql = "SELECT token from ".DB_PREF.AUTH_UTABLE." WHERE uname = :uname";
		$data = array(':uname' => $uname);		
	
		$res = $pdio->parametricQuery($sql, $data);
		
		if (count($res) == 0) {
			return '';
		}
		
		return $res[0]['token'];
	} 
	
	/**
	 * 
	 * @param PDIO $pdio
	 * @param unknown $uname
	 * @param unknown $hpwd
	 * @param unknown $salt
	 */
	public static function register($pdio, $uname, $hpwd, $salt) {
		$sql = "INSERT INTO ".DB_PREF.AUTH_UTABLE." VALUES (:uname, :hpwd, :salt, NULL)";
		$data = array (
			':uname' => $uname,
			':hpwd'  => $hpwd,
			':salt'  => $salt				
		);
		
		return $pdio->parametricQuery($sql, $data);
	}
	
	
}
